package com.tfswx.fljdmxyy.validation;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.HashMap;
import java.util.Map;

/**
 * 不全部为空
 *
 * @author ricky
 * @date 2021/11/30
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NotAllBlank.Validator.class)
public @interface NotAllBlank {


    String[] fields();

    String message() default "{path}-{fields}-不能全部为空";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @Slf4j
    class Validator implements ConstraintValidator<NotAllBlank, Object> {

        String[] fields;

        @Override
        public void initialize(NotAllBlank constraintAnnotation) {
            fields = constraintAnnotation.fields();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            if (value == null) {
                return true;
            }

            for (String field : fields) {
                Object kssjObj = BeanUtil.getProperty(value, field);
                if (StringUtils.isNotBlank(String.valueOf(kssjObj))) {
                    return true;
                }
            }
            Map<String, Object> map = new HashMap<>();
            map.put("fields", fields);
            ValidUtil.setParam(context, map);
            return false;
        }
    }
}
